<template>
  <!-- 跟标签节点 -->
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="query">
        <el-form-item>
          <el-input v-model="query.keywords" placeholder="部门名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>


    <!--列表-->
    <el-table :data="dataList" highlight-current-row v-loading="listLoading" @selection-change="selsChange"
              style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="name" label="部门名称" width="120" sortable>
      </el-table-column>
      <el-table-column prop="intro" label="部门简介" width="120" sortable>
      </el-table-column>
      <el-table-column prop="create_time" label="部门创建时间" width="220" sortable>
      </el-table-column>
      <el-table-column prop="update_time" label="部门修改时间" width="220" sortable>
      </el-table-column>
      <el-table-column prop="manager.username" label="部门经理" sortable>
      </el-table-column>
      <el-table-column prop="parent.name" label="上级部门" sortable>
      </el-table-column>
      <el-table-column prop="state" label="状态" :formatter="formatState" sortable>
      </el-table-column>
      <el-table-column prop="path" label="路径" sortable>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>


    <!--分页条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
          :page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          @size-change="handleSizeChange"
          :total="total" style="float:right;">
      </el-pagination>
    </el-col>

    <!-- 添加和编辑的弹出框 -->
    <el-dialog :title="title" :visible.sync="formVisible" :close-on-click-modal="false">
      <el-form :model="deptForm" label-width="80px" :rules="deptFormRules" ref="deptForm">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="deptForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="部门简介">
          <el-input v-model="deptForm.intro"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="deptForm.state">
            <el-radio class="radio" :label="1">启用</el-radio>
            <el-radio class="radio" :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="部门经理">
          <!--          <el-input  v-model="deptForm.manager_id"></el-input>-->
          <el-select v-model="deptForm.manager" value-key="id" clearable filterable placeholder="请选择">
            <el-option
                v-for="emp in emps"
                :key="emp.id"
                :label="emp.username"
                :value="emp">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上级部门">
          <!--<el-input  v-model="deptForm.parent_id"></el-input>-->
          <el-cascader
              v-model="deptForm.parent"
              :options="deptTree"
              :props="{
							   checkStrictly: true,
							   label:'name',
							   value:'id'
							}"
              clearable
          >
          </el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="formVisible = false">取消</el-button>
        <el-button type="primary" @click.native="formSubmit" :loading="deptFormLoading">提交</el-button>
      </div>
    </el-dialog>
  </section>

</template>

<script>
import util from "../../common/js/util";
import {addUser} from "../../api/api";

export default {
  name: "Department",
  data() {
    return {
      query: {
        keywords: null
      },
      dataList: [],
      listLoading: false,
      sels: [],
      total: 0,
      currentPage: 2,
      pageSize: 5,
      title: "新增",
      formVisible: false, //默认关闭弹出框
      deptForm: {
        id: null,
        name: null,
        intro: null,
        manager_id: null,
        parent_id: null,
        state: null,
        path: null,
        manager: null,
        parent: null
      },
      deptFormRules: {
        name: [
          {required: true, message: '请输入部门名称', trigger: 'blur'}
        ]
      },
      deptFormLoading: false,
      emps: [],
      deptTree: []

    }
  },
  methods: {
    batchRemove() {
      //触发批量删除操作
      var ids = this.sels.map(item => item.id)
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        //NProgress.start();
        //let para = { ids: ids };
        this.$http.patch("/dep", ids).then((res) => {
          this.listLoading = false;
          //NProgress.done();
          this.$message({
            message: '删除成功',
            type: 'success'
          });
          this.loadList();
        });
      }).catch(() => {
      });
    },
    //提交弹出框的效果
    formSubmit() {
      this.$refs.deptForm.validate((valid) => {
        if (valid) {//通过表单验证
          this.$confirm('确认提交数据吗？', '提示', {}).then(() => {
            //确认框 用户点击了确认
            this.deptFormLoading = true;
            //对parent 做特殊处理哦
            //1.选择了级联    null   [1]  [1,2]
            if (this.deptForm.parent) {
              //2.取出最后一个值
              let index = this.deptForm.parent.length;
              //改变parent的数据结构   parent:{ id:1}
              this.deptForm.parent = {
                id: this.deptForm.parent[index - 1]
              }
            }

            this.$http.put("/dep", this.deptForm).then((res) => {
              if (res.data.success) {
                this.$message({
                  message: '提交成功',
                  type: 'success'
                });
              } else {
                this.$message.error(res.data.message);
              }
              //关闭弹出框
              this.formVisible = false;
              this.loadList();
              this.deptFormLoading = false;

            });
          });
        }
      });
    },
    search() {
      this.currentPage = 1;
      console.log("搜")
      this.loadList();
    },
    handleAdd() {
      this.loadDeptTree();
      //1.清空表单数据
      this.deptForm = {
        id: null,
        name: null,
        intro: null,
        manager_id: null,
        parent_id: null,
        state: null,
        path: null
      }
      //2.打开弹出框
      this.formVisible = true;

    },
    selsChange(sels) {
      this.sels = sels
    },
    //性别显示转换
    formatState: function (row, column) {
      return row.state == 1 ? '启用' : '废弃';
    },
    handleEdit(index, row) {
      this.loadDeptTree();
      //1.做数据的回显
      Object.assign(this.deptForm, row);
      //2.打开弹出框
      this.formVisible = true;
      //3.对上级部门做数据回显
      this.deptForm.parent = row.parent_id
    },
    handleDel(index, row) {
      this.$confirm('确认删除数据吗？', '提示', {
        type: 'warning'
      }).then(() => {
        //确认框 用户点击了确认
        this.$http.delete("/dep/" + row.id).then((res) => {
          if (res.data.success) {
            this.$message({
              message: '删除成功',
              type: 'success'
            });
          } else {
            this.$message.error(res.data.message);
          }
          this.loadList();
        });
      });
    },
    loadList() {
      //加载列表数据
      this.listLoading = true
      //封装请求数据
      let query = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        keywords: this.query.keywords
      }
      //发送请求获取列表数据
      this.$http.post("/dep", query).then(res => {
        console.log(res.data.data.data)
        this.dataList = res.data.data.data;
        this.total = res.data.data.total;
        //关闭加载效果
        this.listLoading = false;
      })
    },
    handleCurrentChange(num) {
      this.currentPage = num;
      this.loadList();
    },
    handleSizeChange(num) {//当用户切换每页展示的条数的时候触发的方法
      this.pageSize = num;
      this.loadList();
    },
    loadEmployees() {
      //发送请求获取所有的员工
      this.$http.get("/employee").then(res => {
        this.emps = res.data.data;
      })
      console.log(this.emps)
    },
    loadDeptTree() {//加载部门树
      this.$http.get("/dep/tree").then(res => {
        this.deptTree = res.data.data;
      })
    }

  },
  mounted() {
    this.loadList();
    this.loadEmployees();
  }

}

</script>

<style scoped>

</style>
